package com.example.yanke.idcard;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.telpo.tps550.api.TelpoException;
import com.telpo.tps550.api.idcard.IdCard;
import com.telpo.tps550.api.idcard.IdentityMsg;

import androidx.annotation.NonNull;

/**
 * Created By kzz on 2021/8/13
 * Describe:
 */
public class YKIDCardManager {
    private Context mContext;
    private IDCardResultListener idCardResultListener;
    private IdCard mIdCard;
    private static final int READ_SUCCESS = 0;
    private static final int READ_FAILS = 1;
    private boolean isRead = false;
    private boolean isStop = false;
    private ReadThread mReadThread;

    public YKIDCardManager(Context mContext, IDCardResultListener idCardResultListener) {
        this.mContext = mContext;
        this.idCardResultListener = idCardResultListener;
        this.mIdCard = new IdCard(mContext);
    }

    public IdCard getIdCard() {
        return mIdCard;
    }

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case READ_SUCCESS:
                    IdentityMsg info = (IdentityMsg) msg.obj;
                    if (idCardResultListener != null)
                        idCardResultListener.result(mIdCard, info);
                    isStop = false;
                    break;
                case READ_FAILS:
                    isStop = false;
                    Log.d("证件阅读器", (String) msg.obj);
                    break;

            }
            return false;
        }
    });

    /**
     * 单次读取身份证信息
     */
    public void readInfo() {
        Thread mThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Message msg = new Message();
                    if (mIdCard != null) {
                        IdentityMsg info = mIdCard.checkIdCardOverseas();
                        if (info != null) {
                            if (!TextUtils.isEmpty(info.getName())) {
                                info.setName(info.getName().replaceAll("\\s*", ""));
                            }
                            if (!TextUtils.isEmpty(info.getSex())) {
                                if (info.getSex().contains("女") || info.getSex().contains("F") || info.getSex().contains("f")) {
                                    info.setSex("女");
                                } else {
                                    info.setSex("男");
                                }
                            }
                            msg.what = READ_SUCCESS;
                            msg.obj = info;
                        } else {
                            msg.what = READ_FAILS;
                            msg.obj = "未读取到身份证信息";
                        }
                    } else {
                        msg.what = READ_FAILS;
                        msg.obj = "身份证阅读器未初始化";
                    }
                    mHandler.sendMessage(msg);
                } catch (TelpoException e) {
                    e.printStackTrace();
                }

            }
        });
        mThread.start();
    }

    class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (isRead) {
                if (!isStop) {
                    Message msg = new Message();
                    try {
                        if (mIdCard != null) {
                            boolean isFindCard = mIdCard.findCard();
                            if (isFindCard) {
                                isStop = true;
                                IdentityMsg info = mIdCard.checkIdCardOverseas();
                                if (info != null) {
                                    if (!TextUtils.isEmpty(info.getName())) {
                                        info.setName(info.getName().replaceAll("\\s*", ""));
                                    }
                                    if (!TextUtils.isEmpty(info.getSex())) {
                                        if (info.getSex().contains("女") || info.getSex().contains("F") || info.getSex().contains("f")) {
                                            info.setSex("女");
                                        } else {
                                            info.setSex("男");
                                        }
                                    }
                                    msg.obj = info;
                                    msg.what = READ_SUCCESS;
                                } else {
                                    msg.obj = "未读取到身份证信息";
                                    msg.what = READ_FAILS;
                                }
                            } else {
                                msg.obj = "未检测到身份证";
                                msg.what = READ_FAILS;
                            }
                        } else {
                            msg.obj = "身份证阅读器未初始化";
                            msg.what = READ_FAILS;
                        }
                    } catch (TelpoException e) {
                        e.printStackTrace();
                        msg.obj = e.toString();
                        msg.what = READ_FAILS;
                    } finally {
                        mHandler.sendMessage(msg);
                        try {
                            sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }
    }

    /**
     * 开启循环读取
     */
    public void readLoop() {
        if (mReadThread == null) {
            isRead = true;
            mReadThread = new ReadThread();
            mReadThread.start();
        }
    }

    /**
     * 停止循环读取
     */
    public void stopReadThread() {
        if (mReadThread != null && (mReadThread.isAlive())) {
            mReadThread.interrupt();
            isRead = false;
            mReadThread = null;
        }
    }

    /**
     * 释放读卡器，关闭
     */
    public void releaseIDCard() {
        if (mIdCard != null) {
            mIdCard.usbClose();
        }
    }
}
